//
// Created by dong on 2025/10/20.
//

#include "demo101.h"
#include "Swindow.h"

SDL_Window* Swindow::window=nullptr;
SDL_Renderer* Swindow::render=nullptr;
SobjList Swindow::mObjList;

Swindow::Swindow()
{
    if (!Swindow::init())
    {
        SDL_Log("Init error");
        exit(0);
    }

    window = SDL_CreateWindow("test",WINDOW_X,WINDOW_Y,WINDOW_WIDTH,WINDOW_HEIGHT,SDL_WINDOW_SHOWN);
    render = SDL_CreateRenderer(window, -1,SDL_RENDERER_SOFTWARE);

}

void Swindow::setTitle(string name)
{
    this->title = name;
}

Swindow::~Swindow()
{
    close();
}

void Swindow::setBkColor(const SDL_Color& color)
{
    this->color = color;
}

int Swindow::exec()
{
    bool isRunning=true;
    while (isRunning==true)
    {

        SDL_Event msg;
        if (SDL_PollEvent(&msg)!=0)
        {
            switch (msg.type)
            {
            case SDL_QUIT:
                isRunning=false;
                break;
            }
        }

        SDL_SetRenderDrawColor(Swindow::render,color.r,color.g,color.b,0);
        SDL_RenderClear(Swindow::render);

        int size =getSObjectList().size();
        for (int i=0;i<size;i++)
        {
            getSObjectList()[i]->event(&msg);
        }


        SDL_RenderPresent(render);

    }


    return 0;
}

bool Swindow::init()
{
    if (SDL_Init(SDL_INIT_EVENTS) < 0){
        SDL_Log("SDL init error");
        //exit(0);
        return false;
    }
    if (IMG_Init(IMG_INIT_AVIF) <0)
    {
        SDL_Log("Image init error");
        // exit(0);
        return false;
    }
    if (TTF_Init()!=0)
    {
        SDL_Log("TTF init error");
        // exit(0);
        return false;
    }
    if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY,MIX_DEFAULT_FORMAT,2,1024)!=0)
    {
        SDL_Log("Mix Init error");
        // exit(0);
        return false;
    }

    SDL_Log("init success");
    return  true;
}

void Swindow::close()
{
    SDL_Quit();
    IMG_Quit();
    TTF_Quit();
    Mix_CloseAudio();
    Mix_Quit();
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(render);

}
